<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="12" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="70px">
          <el-form-item label="校区" prop="schoolId">
            <treeselect v-model="queryParams.schoolId" :options="deptOptions" :normalizer="normalizer" placeholder="选择校区" style="width:100px"/>
          </el-form-item>
          <el-form-item label="班级名称" prop="classesName">
            <el-input
              v-model="queryParams.classesName"
              placeholder="输入班级"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
              style="width:50%"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
            <el-button icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
          </el-form-item>
        </el-form>
        <el-table v-loading="loading" :data="classesList" @row-click="handleRowClick" row-key="id" highlight-current-row>
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="所属校区" align="left" prop="schoolId" :formatter="getSchool" :show-overflow-tooltip="true"/>
          <el-table-column label="班级名称" align="left" prop="classesName" :show-overflow-tooltip="true"/>
          <el-table-column label="默认单次金额" align="right" prop="amount" :show-overflow-tooltip="true"/>
          <el-table-column label="操作老师" align="left" prop="userId" width="200" :formatter="getTeacher" :show-overflow-tooltip="true"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['business:classes:edit']"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['business:classes:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />

        <!-- 添加或修改班级信息对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="110px">
            <el-form-item label="所属校区" prop="schoolId">
              <treeselect v-model="form.schoolId" :options="deptOptions" :normalizer="normalizer" placeholder="选择所属校区" />
            </el-form-item>
            <el-form-item label="班级名称" prop="classesName">
              <el-input v-model="form.classesName" placeholder="请输入班级名称" />
            </el-form-item>
            <el-form-item label="教务老师" prop="jwteacherId">
              <el-select filterable v-model="form.jwteacherId" placeholder="请选择教务老师" clearable size="small">
                <el-option v-for="dict in teacherList" :key="dict.userId" :label="dict.userName+':'+dict.phonenumber" :value="dict.userId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="教学老师" prop="jxteacherId">
              <el-select filterable v-model="form.jxteacherId" placeholder="请选择教学老师" clearable size="small">
                <el-option v-for="dict in teacherList" :key="dict.userId" :label="dict.userName+':'+dict.phonenumber" :value="dict.userId"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="默认单次金额" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入默认单次金额" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form :model="queryParamsD" ref="queryFormD" :inline="true" v-show="showSearch" label-width="68px">          
          <el-form-item label="学生名称" prop="userName">
            <el-input
              v-model="queryParamsD.userName"
              placeholder="输入学生"
              clearable
              size="small"
              style="width:100px"
              @keyup.enter.native="handleQueryD"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParamsD.phonenumber"
              placeholder="输入号码"
              clearable
              size="small"
              style="width:100px"
              @keyup.enter.native="handleQueryD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQueryD">搜索</el-button>
            <el-button icon="el-icon-plus" size="mini" @click="handleAddD">新增</el-button>
            <el-button icon="el-icon-save" size="mini" @click="submitFormAll">保存</el-button>
          </el-form-item>
        </el-form>  
        <el-table :data="studentList">
          <el-table-column label="学生" align="center" prop="studentId">
            <template slot-scope="scope">
              <el-select filterable v-model="scope.row.studentId" placeholder="请选择学生" clearable style="width:100%">
                <el-option v-for="dict in studentXYList" :key="dict.userId" :label="dict.userName+(dict.phonenumber===null?'':':'+dict.phonenumber)" :value="dict.userId"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="所属班级" align="left" prop="classesId" width="200" :formatter="getClassesXs"/>
          <el-table-column label="入班时间" align="center" prop="createTime" width="200" sortable="custom">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="60">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDeleteD(scope.$index, scope.row)"
                v-hasPermi="['business:activerelate:remove']"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>        
        <pagination
          v-show="totalD>0"
          :total="totalD"
          :page.sync="queryParamsD.pageNum"
          :limit.sync="queryParamsD.pageSize"
          @pagination="getListD"
        />
      </el-col>   
    </el-row>
  </div>
</template>

<script>
import { listClasses, getClasses, delClasses, addClasses, updateClasses, exportClasses } from "@/api/business/classes";
import { listDept } from "@/api/system/dept";
import { listStudentXY, listTeacher, listOpt } from "@/api/system/user";
import { listStudent, delStudent, updateStudentAll } from "@/api/business/student";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Classes",
  components: {
    Treeselect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      totalD: 0,
      // 班级信息表格数据
      classesList: [],
      // 学生所属班级表格数据
      studentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      schoolId: '',//当前选中学校
      classesId: '',//当前选中班级
      deptOptions: [],//学校树选项
      schoolList: [],//学校列表
      teacherList: [],//老师列表
      classesAllList: [],//班级列表
      studentXYList: [],//学生列表
      userList: [],//操作人列表
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        schoolId: null,
        classesId: null,
        classesName: null,
        jwteacherId: null,
        jxteacherId: null,
        amount: null,
      },
      queryParamsD: {
        pageNum: 1,
        pageSize: 10,
        classesId: null,
        userName: null,
        phonenumber: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        amount: [
          { required: true, message: "默认单次金额不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    listDept().then(response => {
        this.schoolList = response.data;
	      this.deptOptions = this.handleTree(response.data, "deptId");
    });
    listTeacher().then(response => {
        this.teacherList = response.rows;
    });
    listClasses().then(response => {
        this.classesAllList = response.rows;
    });
    listStudentXY().then(response => {
        this.studentXYList = response.rows;	      
    });
    listOpt().then(response => {
        this.userList = response.rows;	      
    });
  },
  watch: {
    'form.schoolId': 'currSchoolChange'
  },
  methods: {
    /** 转换学校数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    getSchool(row) {      
      for (let i in this.schoolList) {
        if (this.schoolList[i].deptId === row.schoolId) {
          return this.schoolList[i].deptName;
        }
      }
    },
    getTeacherJw(row) {      
      for (let i in this.teacherList) {
        if (this.teacherList[i].userId === row.jwteacherId) {
          return this.teacherList[i].userName+':'+this.teacherList[i].phonenumber;
        }
      }
    },
    getTeacherJx(row) {      
      for (let i in this.teacherList) {
        if (this.teacherList[i].userId === row.jxteacherId) {
          return this.teacherList[i].userName+':'+this.teacherList[i].phonenumber;
        }
      }
    },
    getClassesXs(row) {      
      for (let i in this.classesAllList) {
        if (this.classesAllList[i].id === row.classesId) {
          return this.classesAllList[i].classesName;
        }
      }
    },
    getTeacher(row) {      
      for (let i in this.userList) {
        if (this.userList[i].userId === row.userId) {
          return this.userList[i].userName+':'+this.userList[i].phonenumber;
        }
      }
    },
    currSchoolChange(value) {      
      let param = {deptId: value};
      listTeacher(param).then(response => {
        this.teacherList = response.rows;
      });
    },
    /** 查询班级信息列表 */
    getList() {
      this.loading = true;
      listClasses(this.queryParams).then(response => {
        this.classesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getListD() {
      listStudent(this.queryParamsD).then(response => {
        this.studentList = response.rows;
        this.totalD = response.total;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        schoolId: null,
        classesName: null,
        jwteacherId: null,
        jxteacherId: null,
        amount: null,
        createTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQueryD() {
      this.queryParamsD.pageNum = 1;
      this.getListD();
    },
    handleRowClick(row) {
      this.schoolId = row.schoolId;
      this.classesId = row.id;
      this.queryParamsD = {schoolId: this.schoolId, classesId: this.classesId, pageNum: this.queryParamsD.pageNum, pageSize: this.queryParamsD.pageSize};
      let param = {deptId: this.schoolId}
      listStudentXY(param).then(response => {
        this.studentXYList = response.rows;	      
      });
      listStudent(this.queryParamsD).then(response => {
        this.studentList = response.rows;
        this.totalD = response.total;
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加班级信息";
      this.form.schoolId = this.schoolList[1].deptId;
    },
    handleAddD() {
      let rowStudent = {
        id: null,
        schoolId: this.schoolId,
        classesId: this.classesId,
        studentId: null,
        teacherId: null,
        createTime: null
      }
      this.studentList.push(rowStudent)
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getClasses(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改班级信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateClasses(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addClasses(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
          listTeacher().then(response => {
            this.teacherList = response.rows;
          });
        }
      });
    },
    submitFormAll() {
      this.studentList.forEach(item => {
        item.classesId = this.classesId;
      });      
      updateStudentAll(this.studentList).then(response => {
        this.$modal.msgSuccess("学生加入班级设置成功");
        this.open = false;
        this.getList();
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除班级信息编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delClasses(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
    },
    handleDeleteD(index, row) {
      const ids = row.id || this.ids;
      if (ids === undefined||row.studentId===null) {
        this.studentList.splice(index, 1);
      } else {
        this.$confirm('是否确认删除班级学生"' + row.studentId + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delStudent(ids);
        }).then(() => {
          this.queryParamsD = {schoolId: this.schoolId, classesId: this.classesId, pageNum: this.queryParamsD.pageNum, pageSize: this.queryParamsD.pageSize};
          listStudent(this.queryParamsD).then(response => {
            this.studentList = response.rows;
            this.totalD = response.total;        
          });
          this.$modal.msgSuccess("删除成功");
        })        
      }      
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有班级信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportClasses(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
